package io.renren.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.renren.annotation.LoginUser;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.common.utils.Result;
import io.renren.dao.StockOrderDao;
import io.renren.dao.StockOrdermxDao;
import io.renren.dto.*;
import io.renren.entity.StockOrderEntity;
import io.renren.entity.UserEntity;
import io.renren.service.*;
import io.renren.utils.StringsUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 食材采购表
 *
 * @author 翟文闯 619556390@QQ.com
 * @since 1.0.0 2019-11-22
 */
@Service
public class StockOrderServiceImpl extends CrudServiceImpl<StockOrderDao, StockOrderEntity, StockOrderDTO> implements StockOrderService {
    @Autowired
    private StockOrderService stockOrderService;
    @Autowired
    private StockOrdermxService stockOrdermxService;
    @Autowired
    private StockOrderDao stockOrderDao;
    @Autowired
    private FinanceService financeService;
    @Autowired
    private StockOrdermxDao stockOrdermxDao;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private TemporaryOrderService temporaryOrderService;
    @Autowired
    private TemporaryOrdermxService temporaryOrdermxService;
    @Override
    public QueryWrapper<StockOrderEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<StockOrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.orderByDesc("create_date");
        return wrapper;
    }

    @Override
    public List<StockOrderDTO> home(Map<String, Object> params){
       QueryWrapper<StockOrderEntity> wrapper =new QueryWrapper<>();
       wrapper.orderByAsc("create_date").last("limit 3");
        List<StockOrderEntity> stockOrderEntityList= baseDao.selectList(wrapper);
        return ConvertUtils.sourceToTarget(stockOrderEntityList, StockOrderDTO.class);
    }

    @Override
    public PageData<StockOrderDTO> getOrder(Map<String, Object> params,  UserEntity entity) {
        QueryWrapper<StockOrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq( "ched_id", entity.getId()).orderByDesc("create_date");
        IPage<StockOrderEntity> page = baseDao.selectPage(
                getPage(params, null, false),
                wrapper);
        PageData<StockOrderDTO> pageData = getPageData(page, StockOrderDTO.class);
        return pageData;
    }


    @Override
    public StockOrderDTO get(long id){
       StockOrderEntity  stockOrderEntity =baseDao.selectById(id);
        return ConvertUtils.sourceToTarget(stockOrderEntity, StockOrderDTO.class);
    }

    @Override
    public  Result updateExamine(StockOrderDTO dto,UserEntity userEntity){//, UserEntity userEntity
        int flag=dto.getStatus();
        //如果到货数量或者照片没有传抛出异常
        if(3==flag){
            //如果是订单用餐时间是12之前则图片不必校验
            StockOrderDTO stockOrderDTO = stockOrderService.get(dto.getStockOrderId());
            System.out.println(stockOrderDTO);
            //根据订单id查询供应商，根据供应商的id查询所属食材是否全部报价
            List<StockOrdermxDTO> gyss = stockOrdermxService.gyss(dto.getStockOrderId());
            for (StockOrdermxDTO ordermxDTO:gyss) {
                if(1 == ordermxDTO.getSubStatus()){
                        List<StockOrdermxDTO> stockOrdermxDTOList = stockOrdermxService.detail(ordermxDTO.getStockOrderId(),ordermxDTO.getSupplierId());
                        for (StockOrdermxDTO stockOrdermxDTO:stockOrdermxDTOList) {
                            if(1==ordermxDTO.getIsPayment()) {
                                if (0!=stockOrdermxDTO.getArrivalNum() &&  null == stockOrdermxDTO.getArrivalNum() || StringUtils.isBlank(stockOrdermxDTO.getEntityPhoto())) {
                                    Result result = new Result();
                                    return result;
                                }
                            }
                        }
                }
            }
        }
        if (flag==4){
            dto.setStatus(5);
            dto.setConfirmTime(new Date());
            dto.setChedId(userEntity.getId());
            saveFinance(dto.getStockOrderId(),userEntity.getDeptId());
        } else if (flag==3){

            dto.setStatus(4);
            dto.setReceivingGoodsTime(new Date());
            dto.setStorehouseClerkId(userEntity.getId());
        } else if (flag==1){
            dto.setStatus(2);
            dto.setAuditTime(new Date());
            dto.setCanteenAdminId(userEntity.getId());
        }

        update(dto);

        return new Result();
    }

    /**
     * 修改供应商订单状态
     * @param dto 供应商id 订单id
     * @param userEntity
     * @return
     */
    @Override
    public Result UpdateSupplierStutas(StockOrderDTO dto, UserEntity userEntity) {
        List<StockOrdermxDTO> stockOrdermxDTOList = stockOrdermxDao.selectStockOrdermx(dto.getStockOrderId(), userEntity.getId());
        for (StockOrdermxDTO ordermxDTO:stockOrdermxDTOList) {
            stockOrdermxDao.updateOrder(ordermxDTO.getStockOrdermxId(),1);

        }
        StockOrderDTO stockOrderDTO = stockOrderService.get(dto.getStockOrderId());
            if (2 == stockOrderDTO.getStatus()){
            dto.setStatus(3);
           /* dto.setQuotationTime(new Date());
            dto.setSupplierId(userEntity.getId());*/
            update(dto);
        }
        return new Result();
    }

    /**
     * 生成财务订单
     * @param order
     */
   void saveFinance(Long order,Long canteenId ){
       List<StockOrdermxDTO> stockOrdermxAllList = stockOrdermxDao.gys1(order);
       for (StockOrdermxDTO ordermxDao:stockOrdermxAllList) {
           Float total=0F;
           if(0 != ordermxDao.getSubStatus()){
               List<StockOrdermxDTO> list = stockOrdermxService.selecSupplierOrder1(ordermxDao.getSupplierId(),ordermxDao.getStockOrderId());
               FinanceDTO financeDTO = new FinanceDTO();
               financeDTO.setCreateDate(list.get(0).getCreateDate());
               for (StockOrdermxDTO stockOrdermx: list) {
                   //单价*数量
                   Float mult = StringsUtils.mult(stockOrdermx.getArrivalNum(), stockOrdermx.getUnitPrice());
                   total = total + mult;
               }
               financeDTO.setAmountPayable(total);
               financeDTO.setSupplierId(ordermxDao.getSupplierId());
               financeDTO.setOrderid(ordermxDao.getStockOrderId());
               financeDTO.setCanteenId(canteenId+"");
               financeDTO.setType("1");
               financeService.save(financeDTO);
           }
       }
   }
    @Override
    public PageData<StockOrderDTO> pageAdmin(Map<String, Object> params, UserEntity entity) {
        QueryWrapper<StockOrderEntity> wrapper = new QueryWrapper<>();
        String canteenid = (String)params.get("canteenId");
        wrapper.ge("status",1);
        wrapper.eq(StringUtils.isNotBlank(canteenid),"canteen_id", Long.parseLong(canteenid));
        wrapper.orderByDesc("create_date");
        IPage<StockOrderEntity> page = baseDao.selectPage(
                getPage(params, null, false),
                wrapper
        );
        return getPageData(page, StockOrderDTO.class);
    }

    @Override
    public PageData<StockOrderDTO> pagesTorehouseClerk(Map<String, Object> params, @LoginUser UserEntity entity) {

        QueryWrapper<StockOrderEntity> wrapper = new QueryWrapper<>();
        wrapper.ge("status",3);
        wrapper.eq("canteen_id",entity.getDeptId());
        wrapper.orderByDesc("create_date");
        IPage<StockOrderEntity> page = baseDao.selectPage(
                getPage(params, null, false),
                wrapper
        );
        return getPageData(page, StockOrderDTO.class);
    }
    @Override
    public Map selecSupplierOd(Long supplierId) {
        List<StockOrderDTO> stockOrderlist = stockOrderDao.selectSupplierOed(supplierId);
        ArrayList<StockOrderDTO> stockOrderDTOSList = new ArrayList<>();
        for (StockOrderDTO stockOrderDTO: stockOrderlist ) {
            List<StockOrdermxDTO> list = stockOrdermxService.selecSupplierOrder1(supplierId, stockOrderDTO.getStockOrderId());
            if(list.size()>0){
                StockOrdermxDTO stockOrdermxDTO = list.get(0);
                String deptName = sysDeptService.getDeptName(stockOrderDTO.getCanteenId()).getName()+"每日进货清单";
                stockOrderDTO.setSubStatus(stockOrdermxDTO.getSubStatus());
                stockOrderDTO.setChedRemark(deptName);
                stockOrderDTOSList.add(stockOrderDTO);
            }
        }
        int pending =0;//计算未处理订单的数量
        for (StockOrderDTO stockOrderDTO: stockOrderDTOSList )  {
            if(0 ==stockOrderDTO.getSubStatus()){
                pending = pending+1;
            }
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("pending",pending);
        map.put("list",stockOrderDTOSList);
        return map;
    }


    @Override
    public void deleteOrder(Long id) {
      stockOrderDao.deleteOrder(id);
    }

    @Transactional
    public void saveOrder(JSONObject params,UserEntity entity) {
        String stockOrderId1 = (String) params.get("stockOrderId");
        if (StringUtils.isNotBlank(stockOrderId1)){
            stockOrdermxService.deleteOrder(Long.parseLong(stockOrderId1));
            stockOrderService.deleteOrder(Long.parseLong(stockOrderId1));
        }
        StockOrderDTO stockOrderDTO = new StockOrderDTO();
        String mealTime = (String)params.get("mealTime");
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            Date date = sdf.parse(mealTime);
            stockOrderDTO.setMealTime(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
       // String estimateNum = (String) params.get("estimateNum");
        Integer estimateNum = (Integer) params.get("estimateNum");
        //stockOrderDTO.setEstimateNum(Integer.parseInt(estimateNum));
        stockOrderDTO.setEstimateNum(estimateNum);
        //保存用餐时间，预估人数，供应商Id到 主厨id 主厨备注
        stockOrderDTO.setCreateDate(new Date());
        String chedId = (String) params.get("chedId");
        stockOrderDTO.setChedId(Long.parseLong(chedId));
        stockOrderDTO.setChedRemark((String) params.get("chedRemark"));
        stockOrderDTO.setCanteenId(entity.getDeptId());
        stockOrderService.save(stockOrderDTO);//直接返回插入id
        Long stockOrderId = stockOrderDTO.getStockOrderId();//实体类获取当前id
        ArrayList<LinkedHashMap> list = (ArrayList) params.get("list");
        for(int i=0 ;i<list.size() ;i++){
            LinkedHashMap<String,Object> list1 =list.get(i);
            String supplierId = (String)list1.get("supplierId");
            if(null!=supplierId){
                ArrayList<LinkedHashMap> foods = (ArrayList)list1.get("foods");
                for(int j=0 ;j<foods.size() ;j++){
                    StockOrdermxDTO stockOrdermxDTO = new StockOrdermxDTO();
                    String foodId = (String)foods.get(j).get("foodId");
                    stockOrdermxDTO.setFoodId(Long.parseLong(foodId));
                    stockOrdermxDTO.setSupplierId(Long.parseLong(supplierId));
                    Float num =1F;
                   // Integer purchaseNum =(Integer)foods.get(j).get("purchaseNum");
                    String purchaseNum =String.valueOf(foods.get(j).get("purchaseNum"));
                    if(null !=purchaseNum){
                        num =Float.parseFloat(purchaseNum);
                    }
                    stockOrdermxDTO.setPurchaseNum(num);
                    stockOrdermxDTO.setStockOrderId(stockOrderId);
                    stockOrdermxService.save(stockOrdermxDTO);
                }
            }

        }
        TemporaryOrderDTO temOrder = temporaryOrderService.getTemOrder(0, entity.getId(), entity.getDeptId());
            temporaryOrderService.deleteOrder(0,entity.getDeptId());
            temporaryOrdermxService.deleteOrder(temOrder.getTemporaryId());
    }

    /**
     * 获取待处理的数量
     * @param chedId
     * @param clerkId
     * @param canteenId
     * @param status
     * @return
     */
    @Override
    public StockOrderDTO getTotal(Long chedId, Long clerkId,Long canteenId, int status) {
      String ched_Id="";
      String clerk_Id="";
      String canteen_Id="";
      if(null != chedId){
         ched_Id = " and  ched_id = "+chedId;
      }
      if(null != clerkId){
          clerk_Id = " and  canteen_admin_id = "+clerkId;
      }
      if(null != canteenId){
          canteen_Id = " and  canteen_id = "+canteenId;
      }
        StockOrderDTO total = stockOrderDao.getTotal(ched_Id, clerk_Id, canteen_Id, status);
        return total;
    }

    @Override
    public List<StockOrderDTO> getOrderNum(String bgeinDate,String endDate) {
        List<StockOrderDTO> orderNum = stockOrderDao.getOrderNum(bgeinDate,endDate);
        return orderNum;
    }

    @Override
    public List<StockOrderDTO> getOrder2(String bgeinDate, String endDate, long supplierId) {
        List<StockOrderDTO> order = stockOrderDao.getOrder2(bgeinDate, endDate, supplierId);
        return order;
    }

}